package com.example.bluetoothexample;


import com.example.bluetoothexample.BluetoothLayer.Controller;
import com.example.bluetoothexample.BluetoothLayer.RecieveData;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;

public class MainActivity extends Activity {

    // Debugging
    private static final String TAG = "[MainActivity]";
	private static Button btnLock;
	private static Button btnLight;
	private static Button btnStatistics;
	private static Controller controller;
	private static final int OIL_IS_LOW_STATE = 1;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnLight = (Button)findViewById(R.id.btn_light);
        btnLock = (Button)findViewById(R.id.btn_lock);
        btnStatistics = (Button)findViewById(R.id.btn_statistics); 
        
        btnLock.setOnClickListener(new View.OnClickListener() {
			 
			public void onClick(View v) {
					if(controller.isLockedStatus())
					{
						controller.setUnlocked();
					}else if(!controller.isLockedStatus())
					{
						controller.setLocked();
					}
				
			}
		});
        
        btnLight.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				if(controller.isLightStatus())
				{
					controller.setLightsOff();
				}else if(!controller.isLightStatus())
				{
					controller.setLightsOn();
				}
				
				
			}
		});

        btnStatistics.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent myIntent = new Intent(MainActivity.this, StatisticsActivity.class);
				MainActivity.this.startActivity(myIntent);
				overridePendingTransition(R.anim.push_left_in, R.anim.push_left_in);
				
				
			}
		});
        
        controller = Controller.getInstance(handler);
        
        IntentFilter filter1 = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(dcReciever, filter1); // Don't forget to unregister during onDestroy

    }
    
    // The Handler that gets information back from the BluetoothChatService
    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case OIL_IS_LOW_STATE:
                Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
                Toast.makeText(getApplicationContext(), "OIL_STATE_LOW",
                        Toast.LENGTH_SHORT).show();
                break;
                }
              
                
            }
    };
    /*
     * Create a BroadcastReceiver for ACTION_STATE_CHANGED
     * this gets notified if the bluetooth adapter state changes(if turned on/off and acts accordingly
     */
    // 
    private final BroadcastReceiver dcReciever = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            
            if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,-1)==BluetoothAdapter.STATE_OFF)
            {
            	try {
            		Log.e(TAG,"Bluetooth has been turned off, closing socket");
            		
					controller.getBluetoothSocket().close();
				} catch (Exception e) {
					Log.e(TAG,e.getMessage());
					e.printStackTrace();
				}
            }else if(intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,-1)==BluetoothAdapter.STATE_ON)
            {
            	Log.e(TAG,"Bluetooth has been turned on, socket info:");
            	controller.connectBluetooth();

            	Log.e(TAG,controller.getBluetoothDevice().getName());
            	
            	
            
            }
        }
    };
   
    
    

    
    /*
     * These two methods are invoked from the AsyncTask to update the UI pictures, to match the statusses of doors/lights 
     */
    public static void changeLightPicture(String status)
    {
    	if(status.equals("on")){
    		btnLight.setCompoundDrawablesWithIntrinsicBounds(0,0,0,R.drawable.lighton);
    	}else if(status.equals("off")){
    		btnLight.setCompoundDrawablesWithIntrinsicBounds(0,0,0,R.drawable.lightoff);
    		
    	}
    }
    public static void changeLockPicture(String status)
    {
    	if(status.equals("locked")){
    		btnLock.setCompoundDrawablesWithIntrinsicBounds(0,0,0,R.drawable.locklocked);
    	}else if(status.equals("unlocked")){
    		btnLock.setCompoundDrawablesWithIntrinsicBounds(0,0,0,R.drawable.lockunlocked);
    	}
    }
    
        @Override
    public void onBackPressed() {
            super.onBackPressed();
            overridePendingTransition(R.anim.push_left_in, R.anim.push_left_in);
        }
   
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        if(R.id.menu_settings == item.getItemId())
        {
        	Intent myIntent = new Intent(MainActivity.this, SettingsActivity.class);
			startActivity(myIntent);
        }
		return true;
    }
    
    @Override
    protected void onDestroy() {
    	super.onDestroy();
    	unregisterReceiver(dcReciever);
    }
}
